package com.tiancheng.trade.settlement.controller.api;

import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.settlement.bo.ProductBO;
import com.tiancheng.trade.settlement.mapper.settlement.PaymentOrderBankMapper;
import com.tiancheng.trade.settlement.service.settlement.IFlowSubOrderService;
import com.tiancheng.trade.settlement.service.settlement.IPaymentBillService;
import com.tiancheng.trade.settlement.service.settlement.IReconciliationService;
import com.tiancheng.trade.settlement.util.JacksonJsonUtil;
import com.tiancheng.trade.settlement.vo.settlement.api.PaymentBillVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Auther: liudong
 * @Date: 2024/3/30 17:34
 * @Param ${tags}
 * @Description: 记账接口，支付记账与退款记账
 */
@RestController
@RequestMapping("/api/payment")
@Validated
@Slf4j
public class PaymentBillController {
    @Autowired
    IPaymentBillService billService;

    @Autowired
    IReconciliationService reconciliationService;
    @Autowired
    PaymentOrderBankMapper paymentOrderBankMapper;
    @Resource
    private JacksonJsonUtil jacksonJsonUtil;
    @Autowired
    IFlowSubOrderService subOrderService;

    /**
     * CMQ 记账，真实场景下使用
     *
     * @param recordResult
     * @return
     */
    @PostMapping("/recordPaymentBill")
    public Result recordPaymentBill(@RequestBody String recordResult) {
        log.info("支付记账 data:{}", recordResult);
        Map<String, String> messageMap = jacksonJsonUtil.fromJson(recordResult, Map.class);
        String msgBody = messageMap.get("msgBody");
        Map<String, String> dataMap = jacksonJsonUtil.fromJson(msgBody, Map.class);
        PaymentBillVO billVO = jacksonJsonUtil.fromJson(dataMap.get("data"), PaymentBillVO.class);
        int status = billService.recordBill(billVO);
        if (0 < status) {
            return Result.success();
        } else {
            return Result.fail("流水记账失败");
        }
    }

    /**
     * 更新流水子订单对应的产品编号(因为有些产品没及时维护到商户中心就下单了)
     *
     * @param recordResult
     * @return
     */
    @PostMapping("/updateSubOrderProduct")
    public Result updateSubOrderProduct(@RequestBody String recordResult) {
        log.info("updateSubOrderProduct data:{}", recordResult);
        ProductBO bo = jacksonJsonUtil.fromJson(recordResult, ProductBO.class);
        int count = subOrderService.updateSubOrderProduct(bo);
        if (count > 0) {
            return Result.success(count);
        } else {
            log.info("updateSubOrderProduct 没有更新到数据:{}", count);
            return Result.success("没有更新到数据");
        }
    }
}
